﻿using MediPlatform.Domain.Order;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MediPlatform.Infeartructure
{
    public class MyDbContext : DbContext
    {
        public MyDbContext(DbContextOptions options) : base(options)
        {
        }
        /// <summary>
        ///  问诊单主表
        /// </summary>
        public DbSet<ConsultationOrder> ConsultationOrder { get; set; }
        /// <summary>
        /// 问诊记录表
        /// </summary>
        public DbSet<ConsultationRecord> ConsultationRecord { get; set; }
        /// <summary>
        /// 问诊评价表
        /// </summary>
        public DbSet<ConsultationReview> ConsultationReview { get; set; }
        /// <summary>
        /// 药品订单主表
        /// </summary>
        public DbSet<MedicalOrder> MedicalOrder { get; set; }
        /// <summary>
        /// 药品订单详情表
        /// </summary>
        public DbSet<MedicalOrderItem> MedicalOrderItem { get; set; }
        /// <summary>
        ///  物流追踪表 (可选，用于详细物流轨迹)
        /// </summary>
        public DbSet<MedicalOrderLogisticsTracking> MedicalOrderLogisticsTracking { get; set; }
        /// <summary>
        ///  处方表
        /// </summary>
        public DbSet<Prescription> Prescription { get; set; }
        /// <summary>
        /// 处方流转日志表
        /// </summary>
        public DbSet<PrescriptionLog> PrescriptionLog { get; set; }
        // <summary>
        /// 处方流转订单主表
        /// </summary>
        public DbSet<PrescriptionOrder> PrescriptionOrder { get; set; }
        /// <summary>
        /// 退款申请主表
        /// </summary>
        public DbSet<RefundApplication> RefundApplication { get; set; }
        /// <summary>
        /// 退款日志表
        /// </summary>
        public DbSet<RefundLog> RefundLog { get; set; }
        /// <summary>
        /// 挂号日志表 (可选，用于记录状态变更)
        /// </summary>
        public DbSet<RegistrationLog> RegistrationLog { get; set; }
        /// <summary>
        ///  挂号订单主表
        /// </summary>
        public DbSet<RegistrationOrder> RegistrationOrder { get; set; }
        /// <summary>
        /// 用户表
        /// </summary>
        public DbSet<User> User { get; set; }

        /// <summary>
        /// 配置模型
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 全局配置：将所有datetime2类型映射为datetime
            foreach (var entityType in modelBuilder.Model.GetEntityTypes())
            {
                foreach (var property in entityType.GetProperties())
                {
                    if (property.ClrType == typeof(DateTime) || property.ClrType == typeof(DateTime?))
                    {
                        property.SetColumnType("datetime");
                    }
                    
                    // 将所有nvarchar映射为varchar
                    if (property.ClrType == typeof(string))
                    {
                        var maxLength = property.GetMaxLength();
                        if (maxLength.HasValue && maxLength.Value > 0)
                        {
                            property.SetColumnType($"varchar({maxLength.Value})");
                        }
                        else
                        {
                            property.SetColumnType("longtext");
                        }
                    }
                }
            }

            // 配置表名（使用小写命名）
            modelBuilder.Entity<ConsultationOrder>().ToTable("consultation_order");
            modelBuilder.Entity<ConsultationRecord>().ToTable("consultation_record");
            modelBuilder.Entity<ConsultationReview>().ToTable("consultation_review");
            modelBuilder.Entity<MedicalOrder>().ToTable("medical_order");
            modelBuilder.Entity<MedicalOrderItem>().ToTable("medical_order_item");
            modelBuilder.Entity<MedicalOrderLogisticsTracking>().ToTable("medical_order_logistics_tracking");
            modelBuilder.Entity<Prescription>().ToTable("prescription");
            modelBuilder.Entity<PrescriptionLog>().ToTable("prescription_log");
            modelBuilder.Entity<PrescriptionOrder>().ToTable("prescription_order");
            modelBuilder.Entity<RefundApplication>().ToTable("refund_application");
            modelBuilder.Entity<RefundLog>().ToTable("refund_log");
            modelBuilder.Entity<RegistrationLog>().ToTable("registration_log");
            modelBuilder.Entity<RegistrationOrder>().ToTable("registration_order");
            modelBuilder.Entity<User>().ToTable("user");

            // 配置特定实体
            ConfigureEntities(modelBuilder);
        }

        /// <summary>
        /// 配置所有实体
        /// </summary>
        /// <param name="modelBuilder">模型构建器</param>
        private void ConfigureEntities(ModelBuilder modelBuilder)
        {
            // 配置问诊单实体
            modelBuilder.Entity<ConsultationOrder>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.Id).ValueGeneratedOnAdd();
                entity.Property(e => e.OrderNo).HasColumnType("varchar(64)");
                entity.Property(e => e.PatientId).HasColumnType("bigint");
                entity.Property(e => e.DoctorId).HasColumnType("bigint");
                entity.Property(e => e.HospitalId).HasColumnType("bigint");
                entity.Property(e => e.DepartmentId).HasColumnType("bigint");
                entity.Property(e => e.ConsultationType).HasColumnType("int");
                entity.Property(e => e.Status).HasColumnType("int");
                entity.Property(e => e.AppointmentTime).HasColumnType("datetime");
                entity.Property(e => e.SubmitTime).HasColumnType("datetime");
                entity.Property(e => e.Fee).HasColumnType("decimal(18,2)");
                entity.Property(e => e.DiscountAmount).HasColumnType("decimal(18,2)");
                entity.Property(e => e.ActualPayment).HasColumnType("decimal(18,2)");
                entity.Property(e => e.PaymentMethod).HasColumnType("varchar(20)");
                entity.Property(e => e.PaymentTime).HasColumnType("datetime");
                entity.Property(e => e.RefundAmount).HasColumnType("decimal(18,2)");
                entity.Property(e => e.RefundTime).HasColumnType("datetime");
                entity.Property(e => e.CancelReason).HasColumnType("longtext");
                entity.Property(e => e.ExtraInfo).HasColumnType("longtext");
                entity.Property(e => e.CreatedAt).HasColumnType("datetime");
                entity.Property(e => e.UpdatedAt).HasColumnType("datetime");
            });

            // 配置用户实体
            modelBuilder.Entity<User>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.Id).ValueGeneratedOnAdd();
                entity.Property(e => e.UserId).HasColumnType("varchar(64)").IsRequired();
                entity.Property(e => e.Username).HasColumnType("varchar(50)").IsRequired();
                entity.Property(e => e.Email).HasColumnType("varchar(100)");
                entity.Property(e => e.PhoneNumber).HasColumnType("varchar(20)");
                entity.Property(e => e.PasswordHash).HasColumnType("varchar(255)").IsRequired();
                entity.Property(e => e.Role).HasColumnType("varchar(20)").IsRequired();
                entity.Property(e => e.CreatedAt).HasColumnType("datetime");
                entity.Property(e => e.UpdatedAt).HasColumnType("datetime");
            });

            // 配置药品订单实体
            modelBuilder.Entity<MedicalOrder>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.Id).ValueGeneratedOnAdd();
                entity.Property(e => e.OrderNo).HasColumnType("varchar(64)");
                entity.Property(e => e.UserId).HasColumnType("bigint");
                entity.Property(e => e.TotalAmount).HasColumnType("decimal(18,2)");
                entity.Property(e => e.ActualAmount).HasColumnType("decimal(18,2)");
                entity.Property(e => e.Status).HasColumnType("int");
                entity.Property(e => e.PaymentMethod).HasColumnType("varchar(20)");
                entity.Property(e => e.PaymentTime).HasColumnType("datetime");
                entity.Property(e => e.CancelReason).HasColumnType("longtext");
                entity.Property(e => e.RefundAmount).HasColumnType("decimal(18,2)");
                entity.Property(e => e.RefundTime).HasColumnType("datetime");
                entity.Property(e => e.RefundStatus).HasColumnType("int");
                entity.Property(e => e.DeliveryAddress).HasColumnType("longtext");
                entity.Property(e => e.LogisticsCompany).HasColumnType("varchar(50)");
                entity.Property(e => e.TrackingNumber).HasColumnType("varchar(50)");
                entity.Property(e => e.SignTime).HasColumnType("datetime");
                entity.Property(e => e.ExtraInfo).HasColumnType("longtext");
                entity.Property(e => e.CreatedAt).HasColumnType("datetime");
                entity.Property(e => e.UpdatedAt).HasColumnType("datetime");

                // 配置与用户的关系
                entity.HasOne(e => e.User)
                    .WithMany()
                    .HasForeignKey(e => e.UserId)
                    .OnDelete(DeleteBehavior.Restrict);
            });

            // 配置挂号订单实体
            modelBuilder.Entity<RegistrationOrder>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.Id).ValueGeneratedOnAdd();
                entity.Property(e => e.OrderNo).HasColumnType("varchar(64)");
                entity.Property(e => e.UserId).HasColumnType("bigint");
                entity.Property(e => e.HospitalId).HasColumnType("bigint");
                entity.Property(e => e.DepartmentId).HasColumnType("bigint");
                entity.Property(e => e.DoctorId).HasColumnType("bigint");
                entity.Property(e => e.ScheduleTime).HasColumnType("datetime");
                entity.Property(e => e.Status).HasColumnType("int");
                entity.Property(e => e.Fee).HasColumnType("decimal(18,2)");
                entity.Property(e => e.DiscountAmount).HasColumnType("decimal(18,2)");
                entity.Property(e => e.ActualPayment).HasColumnType("decimal(18,2)");
                entity.Property(e => e.PaymentMethod).HasColumnType("varchar(20)");
                entity.Property(e => e.PaymentTime).HasColumnType("datetime");
                entity.Property(e => e.RefundAmount).HasColumnType("decimal(18,2)");
                entity.Property(e => e.RefundTime).HasColumnType("datetime");
                entity.Property(e => e.CancelReason).HasColumnType("longtext");
                entity.Property(e => e.ExtraInfo).HasColumnType("longtext");
                entity.Property(e => e.CreatedAt).HasColumnType("datetime");
                entity.Property(e => e.UpdatedAt).HasColumnType("datetime");

                // 配置与用户的关系
                entity.HasOne(e => e.User)
                    .WithMany()
                    .HasForeignKey(e => e.UserId)
                    .OnDelete(DeleteBehavior.Restrict);
            });

            // 配置退款申请实体
            modelBuilder.Entity<RefundApplication>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.Id).ValueGeneratedOnAdd();
                entity.Property(e => e.ApplicationNo).HasColumnType("varchar(64)");
                entity.Property(e => e.OrderId).HasColumnType("bigint");
                entity.Property(e => e.UserId).HasColumnType("bigint");
                entity.Property(e => e.Amount).HasColumnType("decimal(18,2)");
                entity.Property(e => e.Status).HasColumnType("int");
                entity.Property(e => e.ApplyTime).HasColumnType("datetime");
                entity.Property(e => e.ProcessTime).HasColumnType("datetime");
                entity.Property(e => e.ProcessorId).HasColumnType("bigint");
                entity.Property(e => e.Remark).HasColumnType("longtext");
                entity.Property(e => e.RefundChannel).HasColumnType("varchar(50)");
                entity.Property(e => e.RefundType).HasColumnType("varchar(50)");
                entity.Property(e => e.ExtraInfo).HasColumnType("longtext");
                entity.Property(e => e.CreatedAt).HasColumnType("datetime");
                entity.Property(e => e.UpdatedAt).HasColumnType("datetime");

                // 配置与用户的关系
                entity.HasOne(e => e.User)
                    .WithMany()
                    .HasForeignKey(e => e.UserId)
                    .OnDelete(DeleteBehavior.Restrict);
            });
        }
    }
}
